package com.qisi.demo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qisi.pojo.alertManager.AlertManagerData;
import com.qisi.services.ISendService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class SenderService implements ISendService, Serializable {

    private String amHost;
    private int amPort;

    public SenderService(String amHost, int amPort)  {
        this.amHost = amHost;
        this.amPort = amPort;

    }

    public static void main(String[] args) throws Exception {
        String alertUrl = String.format("http://%s:%d/api/v1/alerts", "10.6.215.39", 9093);
        SenderService senderService = new SenderService( "10.6.215.39", 9093);

        String para = "[\n" +
                "  {\n" +
                "    \"labels\": {\n" +
                "       \"alertname\": \"DiskRunningFull\",\n" +
                "       \"dev\": \"sda1\",\n" +
                "       \"instance\": \"中文测试\",\n" +
                "       \"route\": \"WEBHOOK\"\n" +
                "     },\n" +
                "     \"annotations\": {\n" +
                "        \"info\": \"The disk sda1 is running full\",\n" +
                "        \"summary\": \"please check the instance example1\"\n" +
                "      },\n" +
                "     \"Source\": {\n" +
                "        \"link\": \"http://www.baidu.com\"\n" +
                "      }\n" +
                "  }\n" +
                "]";

        String post = senderService.doJsonPost(para);
        System.out.println("post = " + post);
    }

    @Override
    public void send(AlertManagerData data) {
        try {

            JSONArray arr = new JSONArray();
            arr.add(data);

            String responseResult = doJsonPost(arr.toJSONString());

            log.info("json: {}, send result: {}", data, responseResult);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送 json 数据的 post 请求
     * @param json 数据内容
     * @return 响应结果
     */
    private String doJsonPost(String json) throws IOException {

        URL url = new URL(String.format("http://%s:%d/api/v1/alerts", this.amHost, this.amPort));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // HttpClient 6.0被抛弃了
        String result = "";
        BufferedReader reader = null;
        try {

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (json != null && !TextUtils.isEmpty(json)) {
                byte[] writebytes = json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(json.getBytes());
                outwritestream.flush();
                outwritestream.close();
                log.info("doJsonPost: {}", conn.getResponseCode());
            }
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader( new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public void close() {

    }
}
